﻿using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi_SY.Entity;
using WebApi_SY.Models;

namespace WebApi_SY.Controllers
{
    /// <summary>
    /// 简单生产入库接口
    /// </summary>
    public class sli_SP_InStockController : ApiController
    {
        public sli_SP_InStockController()
        {

        }

        [System.Web.Http.HttpPost]
        public async Task<object> Insert([Microsoft.AspNetCore.Mvc.FromBody] sli_SP_InStock bill)
        {
            try
            {
                var context = new YourDbContext();
                var header = new sli_SP_InStock
                {
                    FBillNo = bill.FBillNo,
                    FDate = bill.FDate,
                    FLag = 0,  //同步标记
                    FParms = "",//同步参数
                    sli_SP_InStockEntry = bill.sli_SP_InStockEntry.Select(d => new sli_SP_InStockEntry
                    {
                        //fmodelID = bill.Id,
                        FID = d.FID,
                        FMaterialNumber = d.FMaterialNumber,
                        FBatchNo = d.FBatchNo,
                        FWorkShopNumber = d.FWorkShopNumber,
                        FStockNumber = d.FStockNumber,
                        FQty = d.FQty
                    }).ToList()
                };



                context.Sli_SP_InStock.Add(header);
                await context.SaveChangesAsync();
                var dataNull = new
                {
                    code=200,
                    msg = "Success",
                    planid = header.FID,
                    Date = header.FID.ToString() + "保存成功"

                };
                return dataNull;
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(ex.ToString());
            }


        }

        [Microsoft.AspNetCore.Mvc.HttpGet]
        public IHttpActionResult GetTableID(int page = 1, int pageSize = 10, string FBillNo = null)
        {
            var context = new YourDbContext();
            IQueryable<sli_SP_InStock> query = context.Sli_SP_InStock;
            //if (id.HasValue)
            //{
            //    query = query.Where(q => q.Id == id.Value);
            //}
            if (!string.IsNullOrEmpty(FBillNo))
            {
                query = query.Where(q => q.FBillNo.Contains(FBillNo));
            }

            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
            var paginatedQuery = query.OrderByDescending(b => b.FID).Skip((page - 1) * pageSize).Take(pageSize);
            //var query = context.Sli_quality_report_view.Include(a => a.sli_quality_reportentry_view);
           


            var result = query.Select(a => new
            {
                FID = a.FID,
                FBillNo = a.FBillNo,
                FDate = a.FDate,
                FLag = a.FLag,
                FParms = a.FParms
                

            });
            // return Ok(result);
            var response = new
            {
                totalCounts = totalCount,
                totalPagess = totalPages,
                currentPages = page,
                pageSizes = pageSize,
                code = 200,
                msg = "ok",
                data = result,
                // count= query.Count
            };

            return Ok(response);
        }

        [Microsoft.AspNetCore.Mvc.HttpGet]
        public IHttpActionResult GetTableIDALL(int? id = null)
        {
            var context = new YourDbContext();

            var query = context.Sli_SP_InStock_view.Include(a => a.sli_SP_InStockEntry_view);
            if (id.HasValue)
            {
                query = query.Where(q => q.FID == id);

            }


            var result = query.Select(a => new
            {
                Id = a.FID,
                FBillNo = a.FBillNo,
                FDate = a.FDate,
                FLag = a.FLag,
                FParms = a.FParms,
                sli_SP_InStockEntry_view = a.sli_SP_InStockEntry_view.Select(b => new
                {
                    FID = b.FID,
                    FEntryID = b.FEntryID,
                    FMaterialNumber = b.FMaterialNumber,
                    FNAME = b.FNAME,
                    FBatchNo = b.FBatchNo,
                    FWorkShopNumber = b.FWorkShopNumber,
                    FDepName = b.FDepName,
                    FStockNumber = b.FStockNumber,
                    FStockName = b.FStockName,
                    FQty = b.FQty
                    
                })

            });
            // return Ok(result);
            var response = new
            {
                code = 200,
                msg = "ok",
                data = result,
                // count= query.Count
            };

            return Ok(response);
        }


        /// <summary>
        /// 调用金蝶简单生产入库保存接口，根据导入的生成的表头ID读取数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Microsoft.AspNetCore.Mvc.HttpPost]
        public IHttpActionResult DateSync(int id)
        {
            try
            {
                var context = new YourDbContext();
                //Assert.IsTrue((bool)isSuccess, resultJson);
                ApiClient client = new ApiClient("http://36.151.103.130:9000/k3cloud/"); //接口地址
                //ApiClient client = new ApiClient("http://19vs7gv47690.vicp.fun/k3cloud"); //接口地址
                string dbId = "686c8a9a8f58ba"; //账套ID
                bool bLogin = client.Login(dbId, "Administrator", "kingdee123*", 2052);
                if (bLogin)
                {

                    var heard = context.Sli_SP_InStock.FirstOrDefault(p => p.FID == id);   //获取表头单行数据
                    //var FcustomerNumer = context.Sli_bd_customer_view.FirstOrDefault(p => p.FNAME == heard.FCustomerName); //根据客户名称查询客户代码
                    var entity = context.Sli_SP_InStockEntry.Where(p => p.FID == id).OrderBy(p => p.FEntryID);   //获取表体多行数据
                    var entityList = entity.ToList();
                    //var index = 0;
                    string json = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[\"FBillNo\"],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"true\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"Model\":{\"FID\":0,\"FBillType\":{\"FNUMBER\":\"JDSCRK01_SYS\"},\"FDate\":\"2025-06-16 00:00:00\",\"FStockOrgId\":{\"FNumber\":\"100\"},\"FPrdOrgId\":{\"FNumber\":\"100\"},\"FCurrId\":{\"FNumber\":\"PRE001\"},\"FOwnerTypeId0\":\"BD_OwnerOrg\",\"FOwnerId0\":{\"FNumber\":\"100\"},\"FTransferBizTypeId\":{\"FNumber\":\"OverOrgPrdIn\"},\"FEntity\":[{\"FMaterialId\":{\"FNumber\":\"SY-CP-01-001\"},\"FInStockType\":\"1\",\"FUnitID\":{\"FNumber\":\"Pcs\"},\"FMustQty\":1.0,\"FRealQty\":1.0,\"FStockId\":{\"FNumber\":\"01\"},\"FLot\":{\"FNumber\":\"12\"},\"FWorkShopId1\":{\"FNumber\":\"BM000005\"},\"FProductNo\":\"123\",\"FIsAffectCost\":false,\"FOwnerTypeId\":\"BD_OwnerOrg\",\"FOwnerId\":{\"FNumber\":\"100\"},\"FStockUnitId\":{\"FNumber\":\"Pcs\"},\"FStockRealQty\":1.0,\"FBaseUnitId\":{\"FNumber\":\"Pcs\"},\"FBaseRealQty\":1.0,\"FExtAuxUnitQty\":0.0,\"FStockStatusId\":{\"FNumber\":\"KCZT01_SYS\"},\"FSecRealQty\":0.0,\"FBaseMustQty\":1.0,\"FKeeperTypeId\":\"BD_KeeperOrg\",\"FKeeperId\":{\"FNumber\":\"100\"}}]}}";
                    sli_InStock rootObject = JsonConvert.DeserializeObject<sli_InStock>(json);
                    rootObject.Model.FEntity.Clear();
                    rootObject.Model.FDate = heard.FDate;
                    rootObject.Model.FBillNo = heard.FBillNo;

                    //var FBillno = "";
                    foreach (var entitydata in entityList)
                    {
                        //FBillno= entitydata.finquiryNo;
                        //rootObject.Model.FBillNo = entitydata.finquiryNo;
                        EntityItem newEntry = new EntityItem();


                        newEntry.FMaterialId = new NumberField { FNumber = entitydata.FMaterialNumber };
                        newEntry.FInStockType = "1";
                        newEntry.FUnitID = new NumberField { FNumber = "Pcs" };
                        newEntry.FMustQty = entitydata.FQty;
                        newEntry.FRealQty = entitydata.FQty;
                        newEntry.FStockId = new NumberField { FNumber = "01" };
                        //newEntry.FLot = new NumberField { FNumber = entitydata.FBatchNo };//这里的123是示例数据，实际应用中需要根据业务逻辑替换 批次
                        newEntry.FWorkShopId1 = new NumberField { FNumber = entitydata.FWorkShopNumber };   //需要定义车间编号  入库单上
                        newEntry.FProductNo = ""; //直接传工令号
                        newEntry.FIsAffectCost = false;
                        newEntry.FOwnerTypeId = "BD_OwnerOrg";
                        newEntry.FOwnerId = new NumberField { FNumber = "100" };
                        newEntry.FStockUnitId = new NumberField { FNumber = "Pcs" };
                        newEntry.FStockRealQty = entitydata.FQty;
                        newEntry.FBaseUnitId = new NumberField { FNumber = "Pcs" };
                        newEntry.FBaseRealQty = entitydata.FQty;
                        newEntry.FExtAuxUnitQty = 0;
                        newEntry.FStockStatusId = new NumberField { FNumber = "KCZT01_SYS" };
                        newEntry.FSecRealQty = 0;
                        newEntry.FBaseMustQty = entitydata.FQty;
                        newEntry.FKeeperTypeId = "BD_KeeperOrg";
                        newEntry.FKeeperId = new NumberField { FNumber = "100" };
                        // 将新创建的实例添加到FSaleOrderEntry列表中
                        rootObject.Model.FEntity.Add(newEntry);
                    }
                    string newJson = JsonConvert.SerializeObject(rootObject);
                    System.Diagnostics.Debug.WriteLine(newJson);
                    //sJson = "{\"CreateOrgId\":0,\"Numbers\":[\"" + FPrdModel + "\"]}";
                    //string jsonData = "{\"NeedUpDateFields\": [],\"NeedReturnFields\": [],\"IsDeleteEntry\": \"true\",\"SubSystemId\": \"\",\"IsVerifyBaseDataField\": \"False\",\"IsEntryBatchFill\": \"true\",\"ValidateFlag\": \"true\",\"NumberSearch\": \"true\",\"IsAutoAdjustField\": \"False\",\"InterationFlags\": \"\",\"IgnoreInterationFlag\": \"\",\"IsControlPrecision\": \"False\",\"Model\": {\"FBillTypeID\": {\"FNUMBER\": \"XSDD01_SYS\"},\"FDate\": \"2022-04-27 00:00:00\",\"FSaleOrgId\": {\"FNumber\": \"100\"},\"FCustId\": {\"FNumber\": \"SCMKH100001\"},\"FReceiveId\": {\"FNumber\": \"SCMKH100001\"},\"FSaleDeptId\": {\"FNumber\": \"SCMBM000001\"},\"FSalerId\": {\"FNumber\": \"SCMYG000001_SCMGW000001_1\"},\"FSettleId\": {\"FNumber\": \"SCMKH100001\"},\"FChargeId\": {\"FNumber\": \"SCMKH100001\"},\"FSaleOrderFinance\": {\"FSettleCurrId\": {\"FNumber\": \"PRE001\"},\"FIsPriceExcludeTax\": 'true',\"FIsIncludedTax\": 'true',\"FExchangeTypeId\": {\"FNumber\": \"HLTX01_SYS\"}},\"FSaleOrderEntry\": [{\"FRowType\": \"Standard\",\"FMaterialId\": {\"FNumber\": \"SCMWL100002\"},\"FUnitID\": {\"FNumber\": \"Pcs\"},\"FQty\": 10,\"FPriceUnitId\": {\"FNumber\": \"Pcs\"},\"FPrice\": 8.849558,\"FTaxPrice\": 10,\"FEntryTaxRate\": 13,\"FDeliveryDate\": \"2022-04-27 15:15:54\",\"FStockOrgId\": {\"FNumber\": \"100\"},\"FSettleOrgIds\": {\"FNumber\": \"100\"},\"FSupplyOrgId\": {\"FNumber\": \"100\"},\"FOwnerTypeId\": \"BD_OwnerOrg\",\"FOwnerId\": {\"FNumber\": \"100\"},\"FReserveType\": \"1\",\"FPriceBaseQty\": 10,\"FStockUnitID\": {\"FNumber\": \"Pcs\"},\"FStockQty\": 10,\"FStockBaseQty\": 10,\"FOUTLMTUNIT\": \"SAL\",\"FOutLmtUnitID\": {\"FNumber\": \"Pcs\"},\"FAllAmountExceptDisCount\": 100,\"FOrderEntryPlan\": [{\"FPlanDate\": \"2022-04-27 15:15:54\",\"FPlanQty\": 10}]}],\"FSaleOrderPlan\": [{\"FRecAdvanceRate\": 100,\"FRecAdvanceAmount\": 100}],\"FBillNo\":" + "\"" + Number + "\"" + ",}}";
                    var result = client.Execute<string>("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save",
                    new object[] { "SP_InStock", newJson });

                    ResultData resultdata = JsonConvert.DeserializeObject<ResultData>(result);
                    if (resultdata.Result.ResponseStatus.IsSuccess)
                    {
                        var FbillNoList = "";
                        foreach (var FbillNo in resultdata.Result.NeedReturnData)
                        {

                            FbillNoList = FbillNoList + FbillNo.FBillNo;
                        }
                        var datas = new
                        {
                            code = 200,
                            msg = "ok",
                            date = "同步成功！简单生产单号：" + FbillNoList + ""
                        };
                        heard.FLag = 1;
                        heard.FParms = newJson;
                        //heard.FReason = FbillNoList;

                        //提交刚创建的销售订单
                        var SubmitsJson = "{\"CreateOrgId\":0,\"Numbers\":[\"" + FbillNoList + "\"]}";
                        var Submitresult = client.Execute<string>("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit",
                        new object[] { "SP_InStock", SubmitsJson });

                        //审核刚创建的销售订单
                        var sJson = "{\"CreateOrgId\":0,\"Numbers\":[\"" + FbillNoList + "\"]}";
                        var Auditresult = client.Execute<string>("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit",
                        new object[] { "SP_InStock", sJson });


                        context.SaveChanges();
                        return Ok(datas);

                    }
                    else
                    {
                        var ErrorList = "";
                        foreach (var Error in resultdata.Result.ResponseStatus.Errors)
                        {

                            ErrorList = ErrorList + Error.Message;
                        }
                        var datas = new
                        {
                            code = 400,
                            msg = "err,同步异常！" + ErrorList + "",
                            date = ""
                        };
                        heard.FLag = 2;
                        heard.FParms = newJson;
                        //heard.FReason = ErrorList;
                        context.SaveChanges();
                        return Ok(datas);
                    }

                }
                else
                {
                    return Ok("登录失败！");
                }

            }
            catch (Exception ex)
            {
                var datas = new
                {
                    code = 400,
                    msg = "失败",
                    date = ex.ToString()
                };
                return Ok(datas);
            }

        }


    }
}